package com.bdqn.t350.ch09;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.t350.ch09.bean.User;
import com.bdqn.t350.ch09.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBootRedisTester {


    @Resource
    RedisTemplate redisTemplate;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    UserService userService;


    @Test
    public void addTest() {
        //redisTemplate.opsForValue().set("name", "zhangsan");
        //stringRedisTemplate.opsForValue().set("age", "18");
        //链式编程
        User user1 = new User();
        user1.setUsrId(1L).setUsrName("lisi").setUsrRoleId(10L);
        User user2 = new User();
        user2.setUsrId(2L).setUsrName("wangwu").setUsrRoleId(12L);
        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());

        String json = (String) JSON.toJSONString(user1);

        redisTemplate.opsForValue().set("user1", json);

        //把List先转换json格式的字符串
        //String s = JSON.toJSONString(list);
        //stringRedisTemplate.opsForValue().set("list", s);
        //String s = stringRedisTemplate.opsForValue().get("list");
        //System.out.println("s:" + s);
        //可以将json格式的字符串转换成对象
        //String parse = (String) JSON.parse(s);
        //List<User> user = JSONObject.parseObject(s, List.class);
        //System.out.println(user);

        //Object zhangsan = redisTemplate.opsForValue().get("zhangsan");
        //System.out.println(zhangsan);


        //stringRedisTemplate.opsForValue().set("lisi",user);


    }

    @Test
    public void getTest() {
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name:" + name);
        String age = stringRedisTemplate.opsForValue().get("age");
        System.out.println("age:" + age);
    }

    @Test
    public void getList() {
        //去redis中获取key为list的值
        List<User> list = (List<User>) redisTemplate.opsForValue().get("list");
        if (list == null) {
            list = userService.selectList(new QueryWrapper());
            redisTemplate.opsForValue().set("list", list);
        }
        System.out.println(list);
    }
}
